package com.cqhilink.iot.jobstandardmanagement.services.innerservice.impl.organization;

import com.cqhilink.api.common.utils.UniqueUtil;
import com.cqhilink.api.common.utils.date.DateStyle;
import com.cqhilink.api.common.utils.date.DateUtil;
import com.cqhilink.api.common.utils.enums.RespCodeEnum;
import com.cqhilink.iot.jobstandardmanagement.facade.service.permission.JsmRolesService;
import com.cqhilink.iot.jobstandardmanagement.facade.utils.OrganizationLevel;
import com.cqhilink.iot.jobstandardmanagement.facade.utils.TreeIconSkin;
import com.cqhilink.iot.jobstandardmanagement.dao.mapper.OrganizationMapper;
import com.cqhilink.iot.jobstandardmanagement.facade.model.*;
import com.cqhilink.iot.jobstandardmanagement.facade.service.department.JsmDepartmentService;
import com.cqhilink.iot.jobstandardmanagement.facade.service.employee.JsmEmployeeService;
import com.cqhilink.iot.jobstandardmanagement.facade.service.enumItem.JsmEnumItemService;
import com.cqhilink.iot.jobstandardmanagement.facade.service.file.JsmFileService;
import com.cqhilink.iot.jobstandardmanagement.facade.service.organization.JsmOrganizationService;
import com.cqhilink.iot.jobstandardmanagement.facade.service.pipeline.JsmPipelineService;
import com.cqhilink.iot.jobstandardmanagement.facade.service.station.JsmStationService;
import com.cqhilink.iot.jobstandardmanagement.facade.service.well.JsmWellService;
import com.cqhilink.iot.jobstandardmanagement.services.innerservice.util.OrgLevelUtils;
import com.cqhilink.iot.jobstandardmanagement.services.innerservice.util.OrgTreeUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * @version V1.0
 * @Package com.cqhilink.iot.jobstandardmanagement.services.innerservice.impl.organization
 * @Description: ${TODO}(组织机构业务逻辑处理)
 * @author: Yu Peng
 * @date: 2016/11/25,0016
 */
public class JsmOrganizationServiceImpl implements JsmOrganizationService {
    //定义持久层dao
    @Autowired
    private OrganizationMapper organizationMapper;
    @Autowired
    private JsmEmployeeService employeeService;
    @Autowired
    private JsmFileService fileService;
    @Autowired
    private JsmWellService wellService;
    @Autowired
    private JsmStationService stationService;
    @Autowired
    private JsmPipelineService pipelineService;
    @Autowired
    private JsmEnumItemService enumItemService;
    @Autowired
    private JsmDepartmentService departmentService;

    @Autowired(required = false)
    private JsmRolesService rolesService ;

    /**
     * 查询组织机构树形list 列表
     *
     * @param id
     * @return
     * @throws Exception
     */
    @Override
    public List<Ztree> queryOrgTree(String id) throws Exception {
        List<Ztree> ztList = new ArrayList<Ztree>();
        List<Organization> orgList = new ArrayList<Organization>();
        if (!StringUtils.isBlank(id)) {
            orgList = organizationMapper.selectOrgByOrgPId(id);
        } else {
            orgList = organizationMapper.selectOrgByLevel("1");
        }
        ztList.addAll(queryOrgTreeByOrgList(orgList));
        return ztList;
    }

    /**
     * 并判断机构是否含有下属机构
     * 将组织机构list转换为orgTree
     *
     * @param orglist
     * @return
     * @throws Exception
     */
    @Override
    public List<Ztree> queryOrgTreeByOrgList(List<Organization> orglist) throws Exception {
        List<Ztree> demotree = new ArrayList<Ztree>();
        for (Organization org : orglist) {
            Ztree demo = new Ztree();
            demo.setId(org.getOrgId());
            demo.setpId(org.getParentOrgId());
            demo.setName(org.getOrgName());
            demo.setOrgLevel(org.getOrgLevelId());
            int levelid = Integer.parseInt(org.getOrgLevelId());
            if (levelid == 1) {
                demo.setIconSkin(TreeIconSkin.ICON_BUIDING.getDesc());
            }
            if (levelid == 2) {
                demo.setIconSkin(TreeIconSkin.ICON_FLAG.getDesc());
            }
            if (levelid == 3) {
                demo.setIconSkin(TreeIconSkin.ICON_OA.getDesc());
            }
            if (levelid == 4) {
                demo.setIconSkin(TreeIconSkin.ICON_STATION.getDesc());
            }
            //判断是否含有下属机构，含有则为true，没有则为false
            int orgNum = organizationMapper.selectCountByPOId(org.getOrgId());
            Boolean isParent = orgNum > 0 ? RespCodeEnum.RESP_CODE_ENUM_true.code() : RespCodeEnum.RESP_CODE_ENUM_false.code();
            demo.setIsParent(isParent);
            demotree.add(demo);
        }
        return demotree;
    }

    /**
     * 根据父节点ID查询下级节点
     *
     * @param orgId
     * @return
     */
    @Override
    public List<Organization> queryNodeByOrgId(String orgId) throws Exception {
        return StringUtils.isBlank(orgId) ? null : organizationMapper.selectOrgByOrgPId(orgId);
    }

    /**
     * 查询组织机构子节点：不显示pipeline和well
     *
     * @param orgId
     * @return
     * @throws Exception
     */
    @Override
    public List<Organization> queryNodeWithoutPipelineWellByOrgId(String orgId) throws Exception {
        return StringUtils.isBlank(orgId) ? null : organizationMapper.selectOrgWithoutPipelineWellByOrgPId(orgId);
    }

    /**
     * 按组织机构ID查找组织机构
     *
     * @return
     * @throws Exception
     */
    @Override
    public Organization findOrgById(String orgid) throws Exception {
        Organization org = organizationMapper.selectByPrimaryKey(orgid);
        if (org != null && org.getOrgLeader() != null) {
            EmployeeSimpleVO emp = organizationMapper.selectEmpByEmpId(org.getOrgLeader());
            org.setLeader(emp);
        }
        return org;
    }


    /**
     * 添加组织机构
     *
     * @return
     * @throws Exception
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED)
    public int addOrg(Organization org, String uploadFiles,
                      String deletedFiles, Employee employee) throws Exception {
        String userId = employee.getEmployeeId();
        String orgId = UniqueUtil.uuid();
        org.setOrgId(orgId);
        org.setCreatorId(userId);
        Date date = new Date();
        org.setCreateDT(DateUtil.DateToString(date, DateStyle.YYYY_MM_DD_HH_MM));
        org.setOperateDT(DateUtil.DateToString(date, DateStyle.YYYY_MM_DD_HH_MM));
        org.setOperateId(userId);
        //保存上传图像
        fileService.addFile(uploadFiles, deletedFiles, orgId);
        int a = organizationMapper.insertSelective(org);
        return a;
    }

    /**
     * 修改组织机构
     *
     * @return
     * @throws Exception
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED)
    public int updateOrg(Organization org, String uploadFiles,
                         String deletedFiles, Employee employee) throws Exception {
        String modifierId = employee.getEmployeeId();
        org.setOperateId(modifierId);
        org.setOperateDT(DateUtil.DateToString(new Date(), DateStyle.YYYY_MM_DD_HH_MM));
        fileService.addFile(uploadFiles, deletedFiles, org.getOrgId());
        return organizationMapper.updateByPrimaryKey(org);
    }

    /**
     * 获取所有组织机构层级列表
     *
     * @return
     * @throws Exception
     */
    @Override
    public List<OrgLevel> queryOrgLevels() throws Exception {
        return organizationMapper.selectOrgLevels();
    }

    /**
     * 验证组织机构是否重名
     * 如果是新增：直接查询数据库是否有值
     * 如果是修改：判断orgId查询的机构名称是否与修改的名称相同
     * 相同则返回true不作任何动作
     * 不同则查询数据库是否有值，有则返回true，无则返回false
     *
     * @param orgId
     * @param orgName
     * @return
     * @throws Exception
     */
    @Override
    public boolean checkOrgName(String orgId, String orgName) throws Exception {
        //如果是添加页面orgId将会为空值，则直接按名称查询机构
        Organization org = StringUtils.isBlank(orgId) ? null : organizationMapper.selectOrgByOrgId(orgId);
        //对orgName进行判空
        if (StringUtils.isBlank(orgName)) {
            return RespCodeEnum.RESP_CODE_ENUM_true.code();
        }
        //如果org有值，就与新修改的名称比对，相同则返回，不同，则继续查询
        if (org != null) {
            if (orgName.trim().equals(org.getOrgName())) {
                return RespCodeEnum.RESP_CODE_ENUM_true.code();
            }
        }
        //按名称查询数据库是否有值
        org = StringUtils.isBlank(orgName) ? null : organizationMapper.selectOrgByName(orgName);
        if (org != null) {
            return RespCodeEnum.RESP_CODE_ENUM_false.code();
        }
        return RespCodeEnum.RESP_CODE_ENUM_true.code();
    }

    /**
     * 按照当前机构的orgId查询出当前机构的层级
     * 再查询出大于该层级的机构层级list
     *
     * @param index
     * @return
     */
    @Override
    public List<OrgLevel> queryOrgLevelsByIndex(String index) {
        Organization org = organizationMapper.selectOrgByOrgId(index);
        return organizationMapper.selectOrgLevelsByIndex((Integer.parseInt(org.getOrgLevelId()) + 1) + "");
    }

    /**
     * 按组织机构ID查找员工列表
     *
     * @param orgId
     * @return
     * @throws Exception
     */
    @Override
    public List<EmployeeSimpleVO> getEmpListByOrgId(String orgId) throws Exception {
        return organizationMapper.selectEmpByOrgId(orgId);
    }


    /**
     * 按给定的机构ID查询机构详情
     *
     * @param orgId
     * @return
     */
    @Override
    public Organization selectOrgByOrgId(String orgId) {
        return organizationMapper.selectOrgByOrgId(orgId);
    }

    /**
     * @param list
     * @Author 卢曼成
     * @Description 批量插入
     * @Date 2017/2/8 18:04
     */
    @Override
    public int insertList(List<Organization> list) {
        return organizationMapper.insertList(list);
    }

    /**
     * @param list
     * @Author 卢曼成
     * @Description 批量修改
     * @Date 2017/2/8 18:04
     */
    @Override
    public int updateList(List<Organization> list) {
        return organizationMapper.updateList(list);
    }

    /**
     * @param list
     * @Author 卢曼成
     * @Description 批量逻辑删除
     * @Date 2017/2/8 17:18
     */
    @Override
    public int deleteList(List<Organization> list) {
        return organizationMapper.deleteList(list);
    }

    /**
     * 根据人员信息
     * 获得当前人员的组织机构
     *
     * @param employee  人员信息
     * @param lessLevel 最小层级
     * @param maxLevel  最大层级
     */
    @Override
    public List<Organization> getOrganizationList(Employee employee, String maxLevel, String lessLevel) throws Exception {
        if (maxLevel == null) maxLevel = OrganizationLevel.ORG_LEVEL_BRANCH.getCode();
        if (lessLevel == null) lessLevel = OrganizationLevel.ORG_LEVEL_PIPELINE.getCode();

        List<Organization> organizationList = new ArrayList<>();
        if (employee != null) {
            /**
             *  查询当前人
             */
            String orgId = employee.getOrgId();
            if (orgId == null) {
                try {
                    EmployeeVo employeeVo = employeeService.findEmployeeById(employee.getEmployeeId());
                    orgId = employeeVo.getOrgId();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            Map resMap = new HashMap<>();
            resMap.put("orgId", orgId);
            resMap.put("maxLevel", maxLevel);
            resMap.put("lessLevel", lessLevel);
            organizationList.addAll(organizationMapper.selectOrgListByEmployee(resMap));
        }
        return organizationList;
    }

    /**
     * @param employee
     * @return 查询人员的所有作业区
     */
    @Override
    public List<Organization> getOrganizationList(Employee employee) throws Exception {
        List<Organization> organizationList = new ArrayList<>();
        Map map = new HashMap<>();
        if (employee.getOrgId() != null) {
            Organization organization = organizationMapper.selectByPrimaryKey(employee.getOrgId());
            if (Integer.parseInt(organization.getOrgLevelId()) <= 3) {
                map.put("isLevel", true);
            } else {
                map.put("isLevel", false);
            }
            map.put("orgId", employee.getOrgId());
            map.put("orgLevel", 3);
            organizationList = organizationMapper.selectDingLevelOrganization(map);
        }

        return organizationList;
    }

    /**
     * 新增机构
     *
     * @param record
     * @return
     */
    @Override
    public int insert(Organization record) {
        return organizationMapper.insert(record);
    }

    /**
     * 新增机构
     *
     * @param record
     * @return
     */
    @Override
    public int insertSelective(Organization record) {
        return organizationMapper.insertSelective(record);
    }

    /**
     * 更新机构
     *
     * @param record
     * @return
     */
    @Override
    public int updateByPrimaryKey(Organization record) {
        return organizationMapper.updateByPrimaryKey(record);
    }

    /**
     * 判断是否为空，更新机构
     *
     * @param record
     * @return
     */
    @Override
    public int updateByPrimaryKeySelective(Organization record) {
        return organizationMapper.updateByPrimaryKeySelective(record);
    }

    /**
     * 删除机构
     *
     * @param orgId
     * @return
     */
    @Override
    public int deleteOrg(String orgId) {
        return organizationMapper.deleteOrg(orgId);
    }

    /**
     * 删除组织机构
     *
     * @return
     * @throws Exception
     */
    @Override
    @Transactional(propagation = Propagation.REQUIRED)
    public int delOrg(String orgId, String orgLevel) throws Exception {



        //查询当前机构下的子机构
        List<Organization> orgList = organizationMapper.selectOrgByOrgPId(orgId);
        //如果不为空及长度大于0,返回-1
        if (orgList != null && orgList.size() > 0) {
            return -1;
        }

        List<Roles> rolesList = rolesService.listRolesByIdOrg(orgId);
        if(rolesList!=null && rolesList.size() > 0){
            return -3;
        }
        int depCount = departmentService.selectCountByPOId(orgId);
        if (depCount > 0) {
            return -2;
        }
        Organization param = organizationMapper.selectOrgByOrgId(orgId);//查询节点
        if (param != null && OrganizationLevel.ORG_LEVEL_BRANCH.getCode().equals(param.getOrgLevel())) {//禁止删除分公司节点
            return -1;
        }
        if (OrganizationLevel.ORG_LEVEL_STATION.getCode().equals(orgLevel)) {
            stationService.updateStatus(orgId);
        } else if (OrganizationLevel.ORG_LEVEL_WELL.getCode().equals(orgLevel)) {
            wellService.updateStatus(orgId);
        }
        return organizationMapper.deleteOrg(orgId);
    }

    /**
     * @return List<String>
     * @Author 卢曼成
     * @Description 查询所有子项
     */
    @Override
    public List<Organization> selectByOrgItem(Organization param) {
        return organizationMapper.selectByOrgItem(param);
    }

    /**
     * 根据ORG查询井或场站或管线信息
     *
     * @param org
     * @param org
     * @Author 卢曼成
     */
    @Override
    public Map queryWellOrStationOrPipeline(Organization org) {
        if (org != null) {
            Map<String, Object> map = new HashMap<String, Object>();
            if (OrgLevelUtils.ORG_LEVEL_WELL.equals(org.getOrgLevelId())) {
                List<EnumItem> wellCategoryList = enumItemService.selectByDataEnumName("井别");//设计井别
                List<EnumItem> wellTypeList = enumItemService.selectByDataEnumName("井型");//设计井型
                List<EnumItem> wellDriveList = enumItemService.selectByDataEnumName("驱动分类");//驱动分类
                List<EnumItem> wellGaugingList = enumItemService.selectByDataEnumName("量油方式");//量油方式
                List<EnumItem> wellOilsList = enumItemService.selectByDataEnumName("油品分类");//油品分类
                Well well = wellService.selectByPrimaryKey(org.getOrgId());
                map.put("wellCategoryList", wellCategoryList);
                map.put("wellTypeList", wellTypeList);
                map.put("wellDriveList", wellDriveList);
                map.put("wellGaugingList", wellGaugingList);
                map.put("wellOilsList", wellOilsList);
                map.put("wellParam", well);
            } else if (OrgLevelUtils.ORG_LEVEL_STATION.equals(org.getOrgLevelId())) {
                List<EnumItem> stationTypeList = enumItemService.selectByDataEnumName("场站类型");//场站类别
                Station station = stationService.selectByPrimaryKey(org.getOrgId());
                map.put("stationParam", station);
                map.put("stationTypeList", stationTypeList);
            }
            return map;
        }
        return null;
    }


    /**
     * 初始化整个组织树
     *
     * @return List<Ztree>
     * @Author 卢曼成
     */
    @Override
    public List<Ztree> initWholeOrgTree(String orgId, String keyword) {
        List<Organization> orgList = new ArrayList<Organization>();
        Organization param = new Organization();
        param.setOrgId(orgId);
        if (StringUtils.isNotEmpty(keyword)) {
            param.setKeyword(keyword);
            orgList = organizationMapper.selectOrgTreeKeyword(param);
        } else {
            orgList = organizationMapper.selectOrgTree(param);
        }
        List<Organization> orgItemList = organizationMapper.selectByOrgItem(param);
        List<Ztree> ztreeList = new ArrayList<Ztree>();
        OrgTreeUtil.orgToTree(orgList, orgItemList, ztreeList, orgId);
        return ztreeList;
    }

    /**
     * 根据组织信息查询组织
     *
     * @param organization
     * @return
     * @throws Exception
     */
    @Override
    public List<Ztree> queryOrgTrees(Organization organization) throws Exception {
        List<Ztree> ztList = new ArrayList<Ztree>();
        List<Organization> orgList = new ArrayList<Organization>();
        if (StringUtils.isNotBlank(organization.getId()) || StringUtils.isNotBlank(organization.getOrgId()) || StringUtils.isNotBlank(organization.getKeyword())) {
            if (StringUtils.isNotBlank(organization.getId())) {
                organization.setKeyword(null);
            }
            orgList = organizationMapper.selectOrgList(organization);
        } else {
            orgList = organizationMapper.selectOrgByLevel("2");
        }
        List<Organization> orgItemList = organizationMapper.selectByOrgItem(null);
        OrgTreeUtil.orgToTree(orgList, orgItemList, ztList);
        return ztList;
    }

    /**
     * 根据组织信息查询组织
     *
     * @param organization
     * @return
     * @throws Exception
     */
    @Override
    public List<Ztree> queryOrgZtrees(Organization organization) throws Exception {
        List<Ztree> ztList = new ArrayList<Ztree>();
        List<Organization> orgList = new ArrayList<Organization>();
        if (StringUtils.isEmpty(organization.getKeyword())) {
            orgList = organizationMapper.selectOrgList(organization);
        } else {
            Organization org = organizationMapper.selectOrgByOrgId(organization.getOrgId());
            if (org != null) {
                organization.setMaxLevelId(org.getOrgLevelId());
                orgList = organizationMapper.selectOrgListLike(organization);
            }
        }
        organization.setOrgLevelId(null);
        List<Organization> orgItemList = organizationMapper.selectByOrgItem(organization);
        OrgTreeUtil.orgToTree(orgList, orgItemList, ztList, organization.getOrgId());
        return ztList;
    }

    /**
     * @param organizationList 组织机构数据集合{用于查询出多组组织机构 和 单个组织机构 }
     * @return listZtree
     */
    @Override
    public List<Ztree> setZtree(List<Organization> organizationList) throws Exception {
        List<Ztree> ztreeList = new ArrayList<>();
        if (organizationList != null && organizationList.size() > 0) {
            for (Organization org : organizationList) {
                Ztree zt = new Ztree();
                zt.setId(org.getOrgId());
                zt.setpId(org.getParentOrgId());
                zt.setName(org.getOrgName());
                if (org.getOrgLevelId().equals(OrganizationLevel.ORG_LEVEL_BRANCH.getCode())) {
                    zt.setIconSkin(TreeIconSkin.getDes(OrganizationLevel.ORG_LEVEL_BRANCH.getCode()));
                } else if (org.getOrgLevelId().equals(OrganizationLevel.ORG_LEVEL_GAS_FIELD.getCode())) {
                    zt.setIconSkin(TreeIconSkin.getDes(OrganizationLevel.ORG_LEVEL_GAS_FIELD.getCode()));
                } else if (org.getOrgLevelId().equals(OrganizationLevel.ORG_LEVEL_WORK_SPACE.getCode())) {
                    zt.setIconSkin(TreeIconSkin.ICON_OA.getDesc());
                } else if (org.getOrgLevelId().equals(OrganizationLevel.ORG_LEVEL_STATION.getCode())) {
                    zt.setIconSkin(TreeIconSkin.getDes("9"));
                } else if (org.getOrgLevelId().equals(OrganizationLevel.ORG_LEVEL_WELL.getCode())) {
                    zt.setIconSkin(TreeIconSkin.getDes("22"));
                } else if (org.getOrgLevelId().equals(OrganizationLevel.ORG_LEVEL_PIPELINE.getCode())) {
                    zt.setIconSkin(TreeIconSkin.getDes("23"));
                }
                zt.setIsParent(true);
                //根据张杰意见：树的前几级最好展开，方便用户无需多次点击
                zt.setOpen(true);
                ztreeList.add(zt);
            }
        }
        return ztreeList;
    }

    /**
     * @param list
     * @return List<String>
     * @Author 卢曼成
     * @Description 根据组织ID查询信息是否存在
     * @CreateDateTime 2017/3/23 18:21
     **/
    @Override
    public List<String> selectByListId(List<Organization> list) {
        return organizationMapper.selectByListId(list);
    }

    /**
     * @param orgId    组织ID
     * @param minLevel 最小层级
     * @param maxLevel 最大曾是
     * @return List<Organization>
     * @Author 卢曼成
     * @Description 根据组织ID查询组织下所有组织数据集合
     * @CreateDateTime 2017/3/27 13:50
     **/
    @Override
    public List<Organization> selectOrgListByEmployee(String orgId, String minLevel, String maxLevel) {
        Map<String, String> map = new HashMap<String, String>();
        map.put("orgId", orgId);
        map.put("maxLevel", maxLevel);
        map.put("lessLevel", minLevel);
        return organizationMapper.selectOrgListByEmployee(map);
    }

    /**
     * 查询自己的组织机构树，并绑定操作
     *
     * @return
     */
    @Override
    public List<Ztree> selectMyOrgs(String orgId, EmployeeVo employee, String keyword) {
        List<Ztree> ztreeList = new ArrayList<>();
        // 组织机构id
        Organization org = null;
        List<Organization> itemList = organizationMapper.selectByOrgItem(org);
        if (StringUtils.isNotEmpty(keyword)) {
            org = new Organization();
            org.setOrgId(employee.getOrgId());
            org.setKeyword(keyword);
            List<Organization> list = organizationMapper.selectOrgTreeKeyword(org);
            OrgTreeUtil.orgToTreeTrue(list, ztreeList, employee.getOrgId());
        } else if (StringUtils.isEmpty(orgId)) {
            org = new Organization();
            org.setParentOrgId(employee.getOrgId());
            List<Organization> list = organizationMapper.selectOrgLists(org);
            OrgTreeUtil.orgToTree(list, itemList, ztreeList, employee.getOrgId());
        } else {
//            // 组织机构不为空的时候，进行ajax判断问题
            List<Organization> list = organizationMapper.selectListByPOId(orgId);
            OrgTreeUtil.orgToTree(list, itemList, ztreeList);
        }
        return ztreeList;
    }

    /**
     * 按机构名称查询机构信息
     *
     * @param orgName
     * @return
     */
    @Override
    public Organization selectOrgByName(String orgName) {
        return organizationMapper.selectOrgByName(orgName);
    }

    /**
     * 获取场站对应的作业区
     *
     * @param orgId
     * @return
     */
    @Override
    public String getUserOrgId(String orgId) {
        return organizationMapper.getUserOrgId(orgId);
    }

    /**
     * 获取场站对应的作业区
     *
     * @param orgId
     * @return
     */
    @Override
    public String getUserOrgParentId(String orgId) {
        return organizationMapper.getUserOrgParentId(orgId);
    }

    /**
     * @param list
     * @param departmentList
     * @Author 卢曼成
     * @Description 接口逻辑添加批量处理
     * @CreateDateTime 2017/3/30 9:02
     **/
    @Override
    @Transactional(propagation = Propagation.REQUIRED)
    public void insertList(List<Organization> list, List<Department> departmentList) {
        if (list.size() > 0) {
            organizationMapper.insertList(list);
        }
        if (departmentList.size() > 0) {
            departmentService.insertList(departmentList);
        }
    }

    /**
     * @param list
     * @param departmentList
     * @Author 卢曼成
     * @Description 接口逻辑修改批量处理
     * @CreateDateTime 2017/3/30 9:02
     **/
    @Override
    @Transactional(propagation = Propagation.REQUIRED)
    public void updateList(List<Organization> list, List<Department> departmentList) {
        if (list.size() > 0) {
            organizationMapper.updateList(list);
        }
        if (departmentList.size() > 0) {
            departmentService.updateList(departmentList);
        }
    }

    /**
     * @param list
     * @param departmentList
     * @Author 卢曼成
     * @Description 接口逻辑删除批量处理
     * @CreateDateTime 2017/3/30 9:02
     **/
    @Override
    @Transactional(propagation = Propagation.REQUIRED)
    public void deleteList(List<Organization> list, List<Department> departmentList) {
        if (list.size() > 0) {
            organizationMapper.deleteList(list);
        }
        if (departmentList.size() > 0) {
            departmentService.deleteList(departmentList);
        }
    }

    /**
     * @param list
     * @return List<Organization>
     * @Author 卢曼成
     * @Description 根据组织条件查询数据集合
     * @CreateDateTime 2017/3/23 18:21
     **/
    @Override
    public List<Organization> selectByOldIdListId(List<Organization> list) {
        return organizationMapper.selectByOldIdListId(list);
    }

    /**
     * 获取当前组织及祖先组织：向上遍历
     *
     * @param
     * @param orgId 组织id
     */
    @Override
    public List<Organization> selectUpByTree(String orgId) {
        if (StringUtils.isEmpty(orgId)) {
            return null;
        } else {
            List<Organization> list = organizationMapper.selectUpByTree(orgId);
            return list;
        }
    }

    /**
     * 获取当前组织及祖先组织：向下遍历
     *
     * @param
     * @param orgId 组织id
     */
    @Override
    public List<Organization> selectDownByTree(String orgId) {
        if (StringUtils.isEmpty(orgId)) {
            return null;
        } else {
            List<Organization> list = organizationMapper.selectDownByTree(orgId);
            return list;
        }
    }

    /**
     * 获取当前组织及后代组织：向下遍历，去除管线和井口
     *
     * @param
     * @param orgId 组织id
     */
    @Override
    public List<Organization> selectDownByTreeWithoutPipelineWell(String orgId) {
        if (StringUtils.isEmpty(orgId)) {
            return null;
        } else {
            List<Organization> list = organizationMapper.selectDownByTreeWithoutPipelineWell(orgId);
            return list;
        }
    }

    /**
     * 获取当前组织及后代组织：向下遍历，去除管线
     *
     * @param
     * @param orgId 组织id
     */
    @Override
    public List<Organization> selectDownByTreeWithoutPipeline(String orgId) {
        if (StringUtils.isEmpty(orgId)) {
            return null;
        } else {
            List<Organization> list = organizationMapper.selectDownByTreeWithoutPipeline(orgId);
            return list;
        }
    }

    /**
     * @param orgIdList 组织机构ID数据组合
     * @param employee  当前登录人员
     * @return 返回组织机构数组集合
     * @throws Exception 异常处理
     */
    @Override
    public List<Organization> selectBottomToTopOrgList(List<String> orgIdList, Employee employee) throws Exception {
        //
        String bottomLevel = "";
        List<Organization> bttOrgList = new ArrayList<>();
        if (StringUtils.isNotEmpty(employee.getOrgId())) {
            Organization myOrg = organizationMapper.selectOrgById(employee.getOrgId());
            bottomLevel = myOrg.getOrgLevelId();
        }
        Map keWordMap = new HashMap<>();
        keWordMap.put("bottomLevel", bottomLevel);
        keWordMap.put("lessLevel", "6");
        Map<String, Organization> isEditOrgList = new HashMap<>();
        if (orgIdList != null && orgIdList.size() > 0) {
            for (String orgId : orgIdList) {
                keWordMap.put("orgId", orgId);
                List<Organization> btOrgList = organizationMapper.selectBottomToTopOrgList(keWordMap);
                if (btOrgList != null && btOrgList.size() > 0) {
                    for (Organization organization : btOrgList) {
                        isEditOrgList.put(organization.getOrgId(), organization);
                    }
                }
            }
        }

        // 读取Map , 进行数据循环取
        Iterator<Map.Entry<String, Organization>> it = isEditOrgList.entrySet().iterator();
        while (it.hasNext()) {
            Map.Entry<String, Organization> entry = it.next();
            //   System.out.println("key= " + entry.getKey() + " and value= " + entry.getValue());
            bttOrgList.add(entry.getValue());
        }
        return bttOrgList;
    }

    /**
     * @param orgId      用户当前orgId
     * @param pOrgId     异步加载orgId
     * @param keyword    模糊搜索条件
     * @param orgLevelId 查询小于当前级别数据
     * @return List<Ztree>
     * @Author 卢曼成
     * @Description
     * @CreateDateTime 2017/5/24 8:59
     */
    @Override
    public List<Ztree> initTree(String orgId, String pOrgId, String keyword, String orgLevelId) {
        List<Ztree> ztreeList = new ArrayList<Ztree>();
        Organization org = new Organization();
        List<Organization> orgList = null;
        if (StringUtils.isNotEmpty(keyword)) {
            org.setOrgId(orgId);
            org.setKeyword(keyword);
            org.setMaxLevelId(orgLevelId);
            orgList = organizationMapper.selectOrgTreeKeyword(org);
            OrgTreeUtil.orgToTreeTrue(orgList, ztreeList, orgId);
        } else if (StringUtils.isNotEmpty(pOrgId)) {
            org.setId(pOrgId);
            org.setOrgLevelId(orgLevelId);
            orgList = organizationMapper.selectOrgList(org);
            List<Organization> itemList = organizationMapper.selectByOrgItem(org);
            OrgTreeUtil.orgToTree(orgList, itemList, ztreeList, orgId);
        } else if (StringUtils.isNotEmpty(orgId)) {
            org.setParentOrgId(orgId);
            org.setOrgLevelId(orgLevelId);
            orgList = organizationMapper.selectOrgLists(org);
            List<Organization> itemList = organizationMapper.selectByOrgItem(org);
            OrgTreeUtil.orgToTree(orgList, itemList, ztreeList, orgId);
        }
        return ztreeList;
    }

    /**
     * 修改组织查询树形方法
     *
     * @param thisId  当前修改组织ID
     * @param orgId   所属人Id
     * @param pOrgId  异步上级ID
     * @param keyword 模糊查询条件
     * @return
     */
    @Override
    public List<Ztree> initEditTree(String thisId, String orgId, String pOrgId, String keyword) {
        Organization param = organizationMapper.selectByPrimaryKey(thisId);
        if (param == null) {
            return null;
        }
        List<Ztree> ztreeList = new ArrayList<Ztree>();
        Organization org = new Organization();
        if (OrgLevelUtils.ORG_LEVEL_STATION.equals(param.getOrgLevelId())) {
            org.setOrgLevelId(OrgLevelUtils.ORG_LEVEL_WELL);
        } else if (OrgLevelUtils.ORG_LEVEL_WELL.equals(param.getOrgLevelId())) {
            org.setOrgLevelId(OrgLevelUtils.ORG_LEVEL_PIPELINE);
        } else {
            org.setOrgLevelId(param.getOrgLevelId());
        }
        List<Organization> orgList = null;
        if (StringUtils.isNotEmpty(keyword)) {
            org.setMaxLevelId(param.getOrgLevelId());
            org.setKeyword(keyword);
            org.setId(thisId);
            org.setOrgId(orgId);
            orgList = organizationMapper.selectEditOrgKeyword(org);
            OrgTreeUtil.orgToTreeTrue(orgList, ztreeList, orgId);
        } else if (StringUtils.isNotEmpty(pOrgId)) {
            org.setId(thisId);
            org.setParentOrgId(pOrgId);
            orgList = organizationMapper.selectEditOrgList(org);
            org.setOrgId(orgId);
            List<Organization> itemList = organizationMapper.selectEditOrgItem(org);
            OrgTreeUtil.orgToTree(orgList, itemList, ztreeList, orgId);
        } else if (StringUtils.isNotEmpty(orgId)) {
            org.setId(thisId);
            org.setOrgId(orgId);
            orgList = organizationMapper.selectEditOrgList(org);
            List<Organization> itemList = organizationMapper.selectEditOrgItem(org);
            OrgTreeUtil.orgToTree(orgList, itemList, ztreeList, orgId);
        }
        return ztreeList;
    }

    @Override
    public String offsetIconSkin(Organization organization) throws Exception {
        String iconSkin = "";
        if (organization != null && StringUtils.isNotEmpty(organization.getOrgLevelId())) {
            iconSkin = OrgTreeUtil.iconSkin(Integer.parseInt(organization.getOrgLevelId()));
        }
        return iconSkin;
    }

    /**
     * 根据条件查询组织
     *
     * @param map
     * @return
     */
    @Override
    public List<Organization> selectDingLevelOrganization(Map<String, Object> map) {
        return organizationMapper.selectDingLevelOrganization(map);
    }

    /**
     * 根据组织ID查询下级组织集合信息
     *
     * @param orgId
     * @return
     */
    @Override
    public List<Organization> selectOrgByOrgPId(String orgId) {
        return organizationMapper.selectOrgByOrgPId(orgId);
    }

    /**
     * 根据组织ID查询下级组织集合信息
     *
     * @param param
     * @return
     */
    @Override
    public List<Organization> selectOrgLists(Organization param) {
        return organizationMapper.selectOrgLists(param);
    }

    @Override
    public List<Organization> queryAllOrgList() throws Exception {
        return organizationMapper.queryAllOrgList();
    }

    /**
     * @param orgId    组织ID
     * @param parentOrgId 上级组织ID
     * @param minLevel 最小层级
     * @param maxLevel 最大曾是
     * @return List<Organization>
     * @Author 卢曼成
     * @Description 根据条件查询组织集合, 用于级联
     * @CreateDateTime 2017/3/27 13:50
     **/
    @Override
    public List<Organization> findByParamCascadeList(String orgId, String parentOrgId, String minLevel, String maxLevel) throws Exception {
        Map<String, String> map = new HashMap<String, String>();
        map.put("orgId", orgId);
        map.put("parentOrgId", parentOrgId);
        map.put("maxLevel", maxLevel);
        map.put("minLevel", minLevel);
        return organizationMapper.selectOrgListByEmployee(map);
    }

    /**
     * 根据组织名称查询组织
     * @return
     * @throws Exception
     */
    @Override
    public Organization queryOrgByOrgName(String orgName) throws Exception {
        List<Organization> organizationList = organizationMapper.queryOrgByOrgName(orgName);

        if(organizationList != null && organizationList.size()>0){
            return organizationList.get(0);
        }else {
            return null;
        }
    }

    /**
     * Author:cp
     * 查询出所有作业区级组织机构
     * 用于app工作动态条件查询
     */
    public List<Organization> getOperationArea(String orgId){
        Organization organization = new Organization();
        if(StringUtils.isNotEmpty(orgId)){
            organization.setOrgId(orgId);
        }
        List<Organization> resultList = organizationMapper.queryOperationArea(organization);
        return resultList;
    }

}
